package com.example.student.controller;


import com.example.student.config.PageParam;
import com.example.student.entity.*;
import com.example.student.service.*;
import com.example.student.utils.JwtUtils;
import com.example.student.utils.ResultBody;
import com.example.student.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@RestController
public class UserController {

    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private UserService userService;
    @Resource
    private StudentService studentService;

    /**
     *
     * 登录接口
     * @author lx
     * @date 2022/1/20 10:56
     * @return
     */
    @PostMapping("/login")
    public ResultBody login(@RequestBody Map<String, String> loginMap){
        String account = loginMap.get("username");
        String password = loginMap.get("password");
        String role = loginMap.get("role");
        String token = "";
        Map<String,Object> map = new HashMap<>();
        // 根据角色判断
        map.put("role",Integer.valueOf(role));
        // 管理员
        if (role.equals("1")){
            User user = userService.getOne(account);
            if (user == null||!password.equals(user.getPassword())){
                return ResultBody.error("用户名密码不正确！");
            }
            map.put("id",user.getId());
            map.put("name",user.getName());
        }
        // 学生
        if (role.equals("2")){
            Student user = studentService.getByNum(account);
            if (user == null||!password.equals(user.getPassword())){
                return ResultBody.error("用户名密码不正确！");
            }
            map.put("id",user.getId());
            map.put("name",user.getName());
        }
        token = jwtUtils.createJwt(map);
        return ResultBody.success(token);
    }

    /**
     * 用户注册
     * @param user
     * @author lx
     * @date 2022/1/20 16:54
     * @return
     */
    @PostMapping(value = "/register")
    public ResultBody register(@RequestBody User user){
        // 学生
        if (user.getRole().equals(2)){
           Student newUser = new Student();
           Student checkUser = studentService.getByNum(user.getAccount());
           if (checkUser!=null){
               return ResultBody.error("学号已存在！");
           }
           newUser.setMajor(user.getMajor());
           newUser.setSex(user.getSex());
           newUser.setGrades(user.getGrades());
           newUser.setFaculty(user.getFaculty());
           newUser.setName(user.getName());
           newUser.setNum(user.getNum());
           newUser.setPassword(user.getPassword());
           this.studentService.add(newUser);
        }

        return ResultBody.success("注册成功，快去登录吧！");
    }

    /**
     * 通过token获取用户信息
     * @param token
     * @author lx
     * @date 2022/1/20 14:51
     * @return
     */
    @GetMapping(value = "/info")
    public ResultBody info(String token){
        if (token==null||"".equals(token)){
            return ResultBody.error("登录已失效！");
        }
        Claims claims = jwtUtils.parseJwt(token);
        String id =String.valueOf(claims.get("id"));
        String role = String.valueOf(claims.get("role"));
        Map<String,Object> data = new HashMap<>();
        // 管理员
        if (role.equals("1")){
            User user = userService.getOneById(id);
            if (user==null){
                return ResultBody.error("当前用户不存在！");
            }
            data.put("id",user.getId());
            data.put("name",user.getName());
            data.put("phone",user.getAccount());
            data.put("role",role);
        }
        // 学生
        if (role.equals("2")){
            Student user = studentService.getOne(id);
            if (user==null){
                return ResultBody.error("当前用户不存在！");
            }
            data.put("id",user.getId());
            data.put("name",user.getName());
            data.put("phone",user.getNum());
            data.put("role",role);
        }
        return ResultBody.success(data);
    }

    /**
     * 用户分页查询
     * @param pageParam
     * @author lx
     * @date 2022/1/20 23:43
     * @return
     */
    @PostMapping(value = "/page")
    public ResultBody page(@RequestBody PageParam pageParam){
        return ResultBody.success(this.userService.page(pageParam));
    }

    /**
     * 用户新增
     * @param user
     * @author lx
     * @date 2022/1/20 16:54
     * @return
     */
    @PostMapping(value = "/add")
    public ResultBody add(@RequestBody User user){
        user.setDeleteFlag(0);
        user.setCreateTime(LocalDateTime.now());
        User checkUserName = this.userService.getOne(user.getAccount());
        if (checkUserName!=null){
            return ResultBody.error("手机号已存在！");
        }
        this.userService.add(user);
        return ResultBody.success("添加成功");
    }

    /**
     * 用户修改
     * @param user
     * @author lx
     * @date 2022/1/20 16:54
     * @return
     */
    @PostMapping(value = "/edit")
    public ResultBody edit(@RequestBody User user){
        User checkUserName = this.userService.getOne(user.getAccount());
        if (checkUserName!=null&& !user.getId().equals(checkUserName.getId())){
            return ResultBody.error("学号已存在！");
        }
        this.userService.update(user);
        return ResultBody.success("修改成功");
    }

    /**
     * 用户删除
     * @param ids
     * @author lx
     * @date 2022/1/20 16:54
     * @return
     */
    @PostMapping(value = "/delete")
    public ResultBody delete(@RequestBody String[]  ids){
        for(String id:ids){
            this.userService.delete(id);
        }
        return ResultBody.success("删除成功");
    }

    /**
     * 密码重置
     * @param ids
     * @author lx
     * @date 2021/1/27 16:54
     * @return
     */
    @PostMapping(value = "/restPassword")
    public ResultBody restPassword(@RequestBody String[]  ids){
        boolean check = this.userService.restPassword(ids);
        if(!check){
            return ResultBody.error("密码重置失败，请联系管理员");
        }
        return ResultBody.success("密码成功重置，重置后密码为：123456");
    }

    /**
     * 用户密码修改
     * @param user
     * @author lx
     * @date 2022/1/20 16:54
     * @return
     */
    @PostMapping(value = "/updatePassword")
    public ResultBody updatePassword(@RequestBody User user){
        // 管理员
        if (user.getRole().equals(1)){
            User checkUser = this.userService.getOneById(UserUtils.getId());
            if (!checkUser.getPassword().equals(user.getOldPassword())){
                return ResultBody.error("原密码不正确，请正确输入密码，如遗忘请联系管理员进行密码重置！");
            }
            checkUser.setPassword(user.getPassword());
            this.userService.update(checkUser);
        }
        // 学生
        if (user.getRole().equals(2)){
            Student checkUser = studentService.getOne(UserUtils.getId());
            if (!checkUser.getPassword().equals(user.getOldPassword())){
                return ResultBody.error("原密码不正确，请正确输入密码，如遗忘请联系管理员进行密码重置！");
            }
            checkUser.setPassword(user.getPassword());
            this.studentService.update(checkUser);
        }
        return ResultBody.success("修改成功");
    }

}
